﻿using System.Security.Cryptography;
using System.Text;

namespace Simple.Common.Helpers
{
    /// <summary>
    /// 配置文件加解密
    /// </summary>
    public class ConfigHelper
    {
        private const string defaultKey = "Q*1_3@c!4kd^j&g%"; //默认密钥
        /// <summary>
        ///  加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string? Encrypt(string str, string key = defaultKey)
        {
            if (string.IsNullOrEmpty(str)) return str;
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

            using var aesAlg = Aes.Create();
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.Mode = CipherMode.ECB;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = aesAlg.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        ///  解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string? Decrypt(string str, string key = defaultKey)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Convert.FromBase64String(str);

            using var aesAlg = Aes.Create();
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.Mode = CipherMode.ECB;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = aesAlg.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.UTF8.GetString(resultArray);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ConfigEncrypt(string cfg, string key = defaultKey)
        {
            if (string.IsNullOrWhiteSpace(cfg)) return string.Empty;
            return $"qhse({ConfigHelper.Encrypt(cfg, key)})";
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ConfigDecrypt(string cfg, string key = defaultKey)
        {
            if (string.IsNullOrWhiteSpace(cfg)) return string.Empty;
            if (cfg.StartsWith("qhse(", StringComparison.CurrentCultureIgnoreCase) && cfg.EndsWith(")"))
            {
                try { return $"{ConfigHelper.Decrypt(cfg[5..^1], key)}"; }
                catch { return cfg; }
            }
            else return cfg;
        }
    }
}
